package org.pan.poi.server;
import java.io.IOException;
import java.net.ServerSocket;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.eclipse.jetty.server.Connector;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.ServerConnector;
import org.eclipse.jetty.util.Jetty;
import org.eclipse.jetty.webapp.WebAppContext;

public class JettyServer {  
    private static final Logger LOGGER = Logger.getLogger(JettyServer.class);  
    private int port;  
    private String contextPath;  
    private String webappPath;  
    private Server server;  
    private WebAppContext webapp;  
  
    /** 
     * 创建用于开发运行调试的Jetty Server, 以src/main/webapp为Web应用目录. 
     */  
    public static void main(String[] args) {  
          
        JettyServer jettyServer = new JettyServer("/ps", "src/main/webapp", 81);  
        jettyServer.start(); 
    	
//    	System.out.println(String.format("%.2f", 23.456));
  
    }  
  
    public JettyServer(String contextPath, String webappPath, int port) {  
        if (StringUtils.isBlank(contextPath)) {  
            this.contextPath = "";  
        }else{  
            this.contextPath = contextPath;  
        }  
        if (StringUtils.isBlank(webappPath)) {  
            throw new IllegalArgumentException("webappPath is required");  
        }else{  
            this.webappPath = webappPath;  
        }  
        this.port = port;  
    }  
  
    public void start()  {  
        if (null == server || server.isStopped()) {  
            doStart();  
        } else {  
            throw new IllegalStateException("JettyServer already started.");  
        }  
    }  
  
    private void doStart()  {  
        if (!checkServerPortAvailable()) {  
            throw new IllegalStateException("Server port already in use: " + port);  
        }  
        
        
        
        
        server = new Server();
        // 设置在JVM退出时关闭Jetty的钩子。
        server.setStopAtShutdown(true);
      
        // 这是http的连接器
        ServerConnector connector = new ServerConnector(server);
        connector.setPort(port);
        // 解决Windows下重复启动Jetty居然不报告端口冲突的问题.
        connector.setReuseAddress(false);
        server.setConnectors(new Connector[] { connector });
        
        
        webapp = new WebAppContext(webappPath, contextPath);  
        
        server.setHandler(webapp);  
        try {  
            long st = System.currentTimeMillis();  
            server.start();  
            long sp = System.currentTimeMillis() - st;  
            System.out.println("JettyServer " + Jetty.VERSION + " started: " + String.format("%.2f sec", sp / 1000D)+",the port is ==="+port+"");  
            server.join();  
        }catch (Exception e){  
            e.printStackTrace();  
            LOGGER.error("JettyServer started failed!");  
        }  
    }  
  
    private boolean checkServerPortAvailable() {  
        if (0 < port) {  
            ServerSocket ss = null;  
            try {  
                ss = new ServerSocket(port, 0, null);  
            } catch (Exception e) {  
                LOGGER.error("check serverPort failed", e);  
                return false;  
            } finally {  
                if (null != ss) {  
                    try {  
                        ss.close();  
                    } catch (IOException e) {  
                        LOGGER.error("close ServerSocket failed", e);  
                    }  
                }  
            }  
        } else {  
            throw new IllegalArgumentException("Invalid port " + port);  
        }  
        return true;  
    }  
  
}  